<template>
  <div>
 
    <form action="/">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @input="change"
      />
    </form>
    <van-cell-group v-show="value!=''">
      <van-cell v-for="(item,index) in zhineng" :key="index" :title="item" @click="clickTit(item)" />
    </van-cell-group>
    <div v-show="value==''">
        <van-cell-group>
      <van-cell title="搜素历史">
        <template #right-icon>
          <div class="item-delete">
            <van-icon name="delete" @click="del" />
          </div>
        </template>
      </van-cell>
    </van-cell-group>
    <div>
      <van-tag
        plain
        type="primary"
        v-for="(item,index) in histroy"
        :key="index"
        style="margin-left:8px"
        @click="clickHistroy(item)"
      >{{item}}</van-tag>
    </div>
    </div>
    
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      imgShow:true,//进入页面是的状态，默认显示
      value: "", //输入搜索的关键字
      histroy: [], //存放搜索历史关键字
      zhineng: [], //智能提示
    };
  },
  mounted() {
    //挂载
    this.histroy = JSON.parse(localStorage.getItem("histroy")) || [];
  },
  methods: {
    onSearch() {
      //确定搜索时触发（并把关键字传到搜索列表中）
      // 判断输入内容不能为空
      if (this.value.trim() == "") {
        return false;
      }
      // 添加
      let rel = true;
      // 判断去重
      this.histroy.map((item) => {
        if (item == this.value) {
          rel = false;
        }
      });
 
      // 搜索历史在页面最多显示3条
      if (rel) {
        if (this.histroy.length >= 3) {
          this.histroy.pop(); //数组末尾删除
          this.histroy.unshift(this.value);
        } else {
          this.histroy.unshift(this.value);
        }
      }
      this.save();
 
      //   跳转页面并传参数到搜索列表页中
      this.$router.push({
        path: "/Brand",
        query: {
          kw: this.value,
        },
      });
      this.value = ""; //添加后清空
    },
    clickTit(item){//点击智能提示
        this.value=item;
        this.onSearch();
    },
    clickHistroy(item){//点击搜索记录
        this.value=item;
        this.onSearch();
    },
    del() {
      //清空（删除历史记录）
      this.$dialog
        .confirm({
          message: "你确定要清空历史记录吗？",
        })
        .then(() => {
          this.histroy = [];
          localStorage.removeItem("histroy");
        })
        .catch(() => {});
    },
    change() {
      //智能事件
      this.zhineng=[];
      this.$axios.get("http://localhost:8080/data.json").then((res) => {
        let lists= res.data.list;
        lists.map(item=>{
            if(item.includes(this.value)){
                this.zhineng.push(item);
            }
        })
      });
    },
    save() {
      //保存到本地
      localStorage.setItem("histroy", JSON.stringify(this.histroy));
    },
  },
};
</script>
 
<style scoped>
</style>